package ext.tianma.bom.service;

import java.beans.PropertyVetoException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import com.ptc.netmarkets.util.misc.NmActionServiceHelper;

import ext.tianma.util.PropertiesUtil;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.content.ContentServerHelper;
import wt.content.FormatContentHolder;
import wt.doc.WTDocument;
import wt.fc.ReferenceFactory;
import wt.fv.FvProperties;
import wt.httpgw.URLFactory;
import wt.util.WTException;

public class ShowDocHelper {

	public static String getDocPath(WTDocument doc) throws WTException, PropertyVetoException {
		
		String domainValue = "codebase" + File.separator + "ext" + File.separator + "tianma" + File.separator + "cfg"
				+ File.separator + "TianmaPro.properties";
		PropertiesUtil ut = new PropertiesUtil(domainValue);
		String domain = ut.getValueByKey("system.domain");
		String filePath = "";
		String MD5 = "";
		ContentItem ci = ContentHelper.service.getPrimary(doc);
		if (ci != null && ci instanceof ApplicationData) {
			ApplicationData applicationdata = (ApplicationData) ci;
			InputStream in = ContentServerHelper.service.findContentStream(applicationdata);
			MD5 = MD5Util.md5Encrypt(in);
		}
		String url = getDocumentUrl(doc);
		filePath = downloadPrimaryContent(doc);
		filePath = domain + File.separator + "temp" + File.separator + "drawing" + File.separator + filePath;
		filePath = filePath.replace("/", File.separator).replace("\\", File.separator);
		
		return filePath;

	}

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * download primary content to temp dir
	 * 
	 * @param document
	 * @return
	 */
	public static String downloadPrimaryContent(WTDocument document) {
		String realPath = "";
		String downloadFile = "";
		InputStream is = null;
		FileOutputStream os = null;
		try {
			ContentHolder contentHolder = ContentHelper.service.getContents((ContentHolder) document);
			ContentItem contentitem = ContentHelper.getPrimary((FormatContentHolder) contentHolder);
			if (contentitem != null) {
				ApplicationData applicationdata = (ApplicationData) contentitem;
				is = ContentServerHelper.service.findContentStream(applicationdata);

				// String folder = getServerTime("yyyyMMdd_HHmmss");
				String folder = "";
				String filePath = MyConstants.DRAWING_DIR + folder + File.separator;

				File targetFile = new File(filePath);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}

				downloadFile = filePath + applicationdata.getFileName();
				// realPath = folder + File.separator + applicationdata.getFileName();
				realPath = folder + applicationdata.getFileName();

				BufferedInputStream bufferedInput = new BufferedInputStream(is);
				os = new FileOutputStream(downloadFile);
				byte[] abyte = new byte[FvProperties.READ_BUFFER_SIZE];

				/**
				 * the total number of bytes read into the buffer, or -1 if there is no more
				 * data because the end of the stream has been reached.
				 */
				int len = -1;
				while ((len = bufferedInput.read(abyte)) > 0) {
					// Writes a portion of an array of bytes.
					os.write(abyte, 0, len);
				}
				os.flush();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return realPath;
	}

	public static String getServerTime(String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		TimeZone zone = new SimpleTimeZone(28800000, "Asia/Shanghai");
		dateFormat.setTimeZone(zone);
		String time = dateFormat.format(new Date());
		return time;
	}

	/**
	 * get document info page url
	 * 
	 * @param doc
	 * @return
	 */
	public static String getDocumentUrl(WTDocument doc) {
		String url = "";
		try {
			ReferenceFactory referencefactory = new ReferenceFactory();
			String oid = referencefactory.getReferenceString(doc);
			URLFactory urlfactory = new URLFactory();
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("oid", oid);
			String action = NmActionServiceHelper.service.getAction("object", "view").getUrl();

			url = urlfactory.getHREF(action, map, true);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return url;
	}

}
